package com.kuiandjie.web;


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.kuiandjie.entity.Employee;
import com.kuiandjie.entity.Goal;
import com.kuiandjie.entity.Log;
import com.kuiandjie.entity.Project;
import com.kuiandjie.service.GoalService;
import com.kuiandjie.service.LogService;
import com.kuiandjie.util.DateUtil;

public class AddGoalServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		
		//获取当前登录对象的权限
		String role = (String) session.getAttribute("role");
		
		if("leader".equals(role)) {
			//获取当前项目
			Project curp = (Project) session.getAttribute("curp");
			
			//判断是不是通过post提交的目标信息
			if("POST".equals(request.getMethod())){
				//设置ajax的接收环境
				response.setContentType("text/html");
				PrintWriter out = response.getWriter();
				
				String goalname = request.getParameter("goalname");
				String desc = request.getParameter("desc");
				//创建一个新的目标存入数据库
				GoalService gs = new GoalService();
				Goal g = new Goal();
				g.setCreateTime(DateUtil.getNow());
				g.setDesc(desc);
				g.setName(goalname);
				g.setProjectId(curp.getId());
				
				gs.addGoal(g);
				
				Employee e = (Employee) session.getAttribute("employee");
				Log log = new Log();
				log.setDesc("添加了目标<a href='projectdetail.jspx'>" + goalname + "</a>");
				log.setEmployeeId(e.getId());
				log.setProjectId(curp.getId());
				log.setTime(DateUtil.getNow());
				log.setName(e.getName());
				log.setPic(e.getPic());
				
				LogService ls = new LogService();
				ls.inserLog(log);
				
				request.setAttribute("msg", new Gson().toJson(log));
				request.getRequestDispatcher("msgflow.jspx").include(request, response);
				//向页面发送信息
				out.print("1");
				out.flush();
				out.close();
				
			}else {
				request.getRequestDispatcher("WEB-INF/views/addgoal.jsp").forward(request, response);
			}
		} else {
			response.sendRedirect("projectdetail.jspx");
		}
	}
}
